package com.yupi.project.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

public class ExcelUtils {
    public static void main(String[] args) throws FileNotFoundException {

    }
    public  static String excelToCsv(MultipartFile multipartFile){
        InputStream file = null;
        try {
            file = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //EasyExcel读取数据
        List<Map<Integer, String>> list = EasyExcel.read(file)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .headRowNumber(0)
                .doReadSync();
        if (CollectionUtils.isEmpty(list)){
            return "";
        }
        System.out.println(list);
        StringBuffer stringBuffer = new StringBuffer();
        LinkedHashMap<Integer, String> head = (LinkedHashMap<Integer, String>) list.get(0);
        List<String> headList = head.values().stream().collect(Collectors.toList());
        stringBuffer.append(StringUtils.join(headList,",")).append("\n");
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> map = (LinkedHashMap<Integer, String>)list.get(i);
            List<String> valueList = map.values().stream().collect(Collectors.toList());
            stringBuffer.append(StringUtils.join(valueList,",")).append("\n");
        }
        return stringBuffer.toString();
    }


}
